package com.fm.demo.activity

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import com.blankj.utilcode.util.*
import com.fm.common.base.BaseBActivity
import com.fm.demo.databinding.ActivityRootBinding
import com.fm.demo.service.ButtonFloatWindowsService

class RootActivity : BaseBActivity<ActivityRootBinding>() {
    private var mService: ButtonFloatWindowsService? = null
    private val mServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            LogUtils.e("Service Disconnected")
            mService = null
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            LogUtils.e("Service Connected")
            service?.let {
                it as ButtonFloatWindowsService.MyBinder
                mService = it.getService()
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        initToolbar(binding.rootToolbar, "自动滑动", true)
        AppUtils.isAppRoot()
        val bindService = bindService(Intent(this, ButtonFloatWindowsService::class.java), mServiceConnection, Context.BIND_AUTO_CREATE)
        LogUtils.e("bind service : $bindService")

        binding.rootStart.setOnClickListener {
            if (!AppUtils.isAppRoot()) {
                ToastUtils.showShort("请同意Root权限请求")
                return@setOnClickListener
            }

            val inputDelayText = binding.rootDelayTime.text.toString()

            if (inputDelayText.isEmpty()) {
                ToastUtils.showShort("请填写延时时间")
                return@setOnClickListener
            }

            val delayTime = inputDelayText.toLong()
            if (delayTime <= 0) {
                ToastUtils.showShort("请输入正确延时时间")
                return@setOnClickListener
            }
            val inputIntervalText = binding.rootIntervalTime.text.toString()

            if (inputIntervalText.isEmpty()) {
                ToastUtils.showShort("请填写刷新时间")
                return@setOnClickListener
            }

            val intervalTime = inputIntervalText.toLong()
            if (intervalTime <= 0) {
                ToastUtils.showShort("请输入正确刷新时间")
                return@setOnClickListener
            }

            mService?.let {
                it.createFloatView()
                it.startRefresh(delayTime, intervalTime)
            }
            moveTaskToBack(true)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        unbindService(mServiceConnection)
    }
}
